<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Sending email in a Servlet</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="jee tutorial, Java, web applications, Java Servlets, Java Mail">
<meta name="description" content="In this part of the Java EE 5 tutorials, we send an email in a Servlet.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Contents">Contents</a>



<h1>Sending email in a Servlet</h1>

<p>
In this part of the JEE tutorials we will send an email using a servlet. 
To work with email, we use the Java Mail API. If we build the example 
with the Netbeans IDE (with the JEE pack), the
necessary jars are provided. Otherwise we need to download the mail.jar 
and the activation.jar files.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 


<h2>Sending email</h2>

<p>
In the next example we fill in the form and send an email. We use the 
Java Mail API. In order to succeed sending an email, we must have a 
gmail account. We use the Google's smtp server to forward
the email. So in the form, we must provide the login and the password of 
our gmail account. The example consists of five files. A css style file 
provides the look and feel for our jsp pages.
The index.jsp is used to fill in the form and send the data to the servlet. 
The EmailServlet processes the
data and tries to send the email to the recipient. If it succeeds, the servlet 
forwards to the success.jsp file.
If not, we receive an error message in error.jsp file. 
</p>

<div class="codehead">style.css</div>
<pre class="code">
* { font-size: 12px; font-family: Verdana }

input, textarea { border: 1px solid #ccc }
textarea { text-align:left}
table { margin-top: 10% }

.error { margin-top: 10%; border: 1px dotted #db1f1f; width: 250px }
.msg { margin-top: 10%; border: 1px dotted #ccc; width: 250px }
</pre>

<p>
This is a stylesheet file. The .error class provides a style for the error message. 
It is a dotted red rectangle. The .msg class is used in the success.jsp file. 
It is a gray dotted rectangle.
</p>

<div class="codehead">index.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
&lt;title&gt;Sending email&lt;/title&gt;
&lt;link rel="stylesheet" href="style.css" type="text/css"&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;center&gt;
&lt;form action="EmailServlet"&gt;   
&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;From&lt;/td&gt;
&lt;td&gt;&lt;input type="text" name="from"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;tr&gt;
&lt;td&gt;To&lt;/td&gt;
&lt;td&gt;&lt;input type="text" name="to"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Subject&lt;/td&gt;
&lt;td&gt;&lt;input type="text" name="subject"&gt;&lt;/td&gt;
&lt;/tr&gt;    
&lt;tr&gt;
&lt;td&gt;Message&lt;/td&gt;
&lt;td&gt;&lt;textarea cols="25" rows="8" name="message"&gt;&lt;/textarea&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Login&lt;/td&gt;
&lt;td&gt;&lt;input type="text" name="login"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Password&lt;/td&gt;
&lt;td&gt;&lt;input type="password" name="password"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;br&gt;
&lt;input type="submit" value="submit"&gt;
&lt;/form&gt;
&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
This is the form for sending the email. There are also inputs for the 
gmail's login and password.
</p>

<img src="/img/java/jee/emailform.png" alt="Email Form">
<div class="figure">Figure: Email Form</div>

<div class="codehead">EmailServlet.java</div>
<pre class="code">
package com.zetcode;

import java.io.*;
import java.net.*;

import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmailServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, 
                                  HttpServletResponse response)
                   throws IOException, ServletException {

        final String err = "/error.jsp";
        final String succ = "/success.jsp";

        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");
        String login = request.getParameter("login");
        String password = request.getParameter("password");

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (MessagingException ex) {
            request.setAttribute("ErrorMessage", ex.getMessage());

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
        }
            RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
            dispatcher.forward(request, response);

    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }
}
</pre>

<p>
This is the servlet, that tries to send the email. 
</p>


<pre class="explanation">
String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String login = request.getParameter("login");
String password = request.getParameter("password");
</pre>

<p>
We get the necessary parameters from the request.
</p>

<pre class="explanation">
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
</pre>

<p>
The properties class is used for configuration. Notice that we set the 
authentication property to true.
</p>

<pre class="explanation">
Authenticator auth = new SMTPAuthenticator(login, password);
</pre>

<p>
We create a new <code>Authenticator</code> class to check the login and the password.
</p>

<pre class="explanation">
Session session = Session.getInstance(props, auth);
</pre>

<p>
We create a new mail session. We provide the properties and the Authenticator.
</p>

<pre class="explanation">
MimeMessage msg = new MimeMessage(session);
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(msg);
</pre>

<p>
Here we create a message. We set the text of the message, subject, sender and 
recipient email addresses. Finally, we send the email message.
</p>

<pre class="explanation">
} catch (AuthenticationFailedException ex) {
    request.setAttribute("ErrorMessage", "Authentication failed");

    RequestDispatcher dispatcher = request.getRequestDispatcher(err);
    dispatcher.forward(request, response);
}
</pre>

<p>
Many things might go wrong, while sending an email. For example we might provide 
a wrong email address or the authentication fails. Here we react to an 
<code>AuthenticationFailedException</code>. If we receive such an exception, 
we set an ErrorMessage attribute to the request and forward to the error.jsp file. 
The ErrorMessage attribute will be used in the error.jsp file.
</p>

<div class="codehead">error.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
    &lt;title&gt;Error&lt;/title&gt;
      &lt;link rel="stylesheet" href="style.css" type="text/css"&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;center&gt;
        &lt;div class="error"&gt;
          &lt;h2&gt;Error&lt;/h2&gt;
            &lt;p&gt;
               Message: &lt;%= request.getAttribute("ErrorMessage") %&gt;    
            &lt;/p&gt;
        &lt;/div&gt;
      &lt;/center&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
This jsp file will be displayed, when an error occurs. The ErrorMessage attribute, 
which was set in the servlet, is displayed.
</p>


<div class="codehead">success.jsp</div>
<pre class="code">
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;

&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Message&lt;/title&gt;
    &lt;link rel="stylesheet" href="style.css" type="text/css"&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;center&gt;
      &lt;div class="msg"&gt;
        &lt;h2&gt;Message&lt;/h2&gt;
          &lt;p&gt;
               Email sent
          &lt;/p&gt;
      &lt;/div&gt;
   &lt;/center&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>

<p>
This is the jsp file, which will be displaed, if no errors occured.
</p>


<p>
In this chapter we have sent an email using a Java Servlet. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 2, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
